<?php

namespace Inbound\Controller;

use \Home\Controller\CommonController;
use Inbound\Service\PublicInfoService;
use Inbound\Service\PublicPlugService;
use Inbound\Service\PrepareneedsService;
use Inbound\Service\InboundshipmentplanService;
use Warehouse\Service\InventoryService;

class StockingApplyController extends CommonController {
    public $prepareneedsService = null;
    public $inboundshipmentplanService = null;
    public $transferHopperAddress = null;
    public $inventory = null;
    public $purchaseOrdersService = NULL;
    public $warehouseOrderService = NULL;

    public function __construct() {
        $this->prepareneedsService = D('Prepareneeds', 'Service');
        $this->inboundshipmentplanService = D('Inboundshipmentplan', 'Service');
        $this->transferHopperAddress = D('TransferHopperAddress','Service');
        $this->inventory = D('Warehouse/Inventory', 'Service');
        $this->purchaseOrdersService = D('Warehouse/PurchaseOrders', 'Service');
        $this->warehouseOrderService = D('Warehouse/StockIn', 'Service');
        parent::__construct();
    }

    /**
     * 描述:界面主页
     */
    public function index() {
        $sites = array();

        if (isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])) {
            if (in_array($_SESSION['current_account']['role_id'], array(3,4))) {
                $accounts = PublicInfoService::salesmanBindAccountsGet($_SESSION['current_account']['id']);

                foreach ($accounts as $acc) {
                    $sites[$acc['id']] = $acc['shorthand_code'];
                }

                $this->assign('accounts', $accounts);
                $this->assign('sites', $sites);
            } else {
                if ($_GET['accountId']) {
                    $salesmanInfo = $this->accountIdBindSalesmanGet($_GET['accountId']);

                    empty($salesmanInfo) && $this->assign('salesman', PublicInfoService::salesmanGet());
                    $this->assign('accountId', $_GET['accountId']);
                    $this->assign('salesman', $salesmanInfo);
                } else {
                    $this->assign('salesman', PublicInfoService::salesmanGet());
                    $this->assign('accountId', 0);
                }
                $this->assign('accounts', PublicInfoService::get_accounts());
            }
        }
        $address = $this->transferHopperAddress->getTransferHopperAddress();
        $this->assign('address', $address);
        $this->assign('enterprise_dominant', PublicInfoService::get_company_array());

        $this->display();
    }

    /**
     *  描述：根据帐号ID查找与帐号绑定的销售员
     */
    public function accountIdBindSalesmanGet($accountId) {
        $salesmanInfo = PublicInfoService::accountIdBindSalesmanGet($accountId);

        return !empty($salesmanInfo) ?  $salesmanInfo : array();
    }

    /**
     * 描述:根据SKU获取SKU产品名称
     */
    public function skuInfoGet() {
        $skuInfo = array();

        $skuTile = PublicInfoService::accountSkuTitleGet($_GET['sku']);
        $skuInfo['name'] = $skuTile;

        echo json_encode($skuInfo);
        exit;
    }


    /**
     * 描述：根据SKU获取实际库存、实际可用库存
     */
    public function skuInventoryGet() {
        $skuInventoryInfo = array();

        if ($_GET['sku']) {
            $site_id = PublicInfoService::get_siteid_by_accountid($_GET['account_id']);
            $condition = array('sku' => trim($_GET['sku']),
                'export_tax_rebate' => $_GET['export_tax_rebate'],
                'enterprise_dominant' => trim($_GET['enterprise_dominant']),
                'site_id' => $site_id
            );

            if ($_GET['export_tax_rebate']) {
                $quantity= $this->inventory->getTaxInventoriesInfo($condition);
                $skuInventoryInfo['quantity'] = $quantity['stock'] ? $quantity['stock'] : 0;
                $skuInventoryInfo['actualQuantity'] =
                    $quantity['actual_available_num'] ? $quantity['actual_available_num'] : 0;
                $skuInventoryInfo['totalActualQuantity'] =
                    $quantity['all_site_num'] ? $quantity['all_site_num'] : 0;
            } else {
                $quantity= $this->inventory->getInventoriesInfo($condition);
                $skuInventoryInfo['quantity'] = $quantity['stock'] ? $quantity['stock'] : 0;
                $skuInventoryInfo['actualQuantity'] =
                    $quantity['actual_available_num'] ? $quantity['actual_available_num'] : 0;
                $skuInventoryInfo['totalActualQuantity'] =
                    $quantity['all_site_num'] ? $quantity['all_site_num'] : 0;
            }

            $occupiedStockingNeedInventory = $this->prepareneedsService->occupiedStockingNeedInventoryGet($_GET);
            $occupiedInventory = $this->inboundshipmentplanService->occupiedInventoryGet($_GET);

            $occupyQuantity = 0;
            if (!empty($occupiedStockingNeedInventory)) {
                foreach ($occupiedStockingNeedInventory as $value) {
                    $occupyQuantity += $value['quantity'];
                }
            }
            if (!empty($occupiedInventory)) {
                foreach ($occupiedInventory as $value) {
                    $occupyQuantity += $value['quantity'];
                }
            }
            $skuInventoryInfo['occupyQuantity'] = $occupyQuantity;

        }

        echo json_encode($skuInventoryInfo);
    }

    /**
     * 描述：调拨库存
     */
    public function moveInventory() {
        $site_id = PublicInfoService::get_siteid_by_accountid($_GET['account_id']);

        $result = array();

        $condition = array(
            'sku' => trim($_GET['sku']),
            'enterprise_dominant' => trim($_GET['enterprise_dominant']),
            'export_tax_rebate' => $_GET['export_tax_rebate'],
            'site_id' => $site_id,
            'quantity' => trim($_GET['needQuantity'])
        );

        $result = $this->inventory->auto_move_site($condition);

        echo json_decode($result);

    }

    /**
     *描述:根据关键词获取SKU列表
     */
    public function skuAutoComplete() {
        $re = array();

        $skus = PublicInfoService::accountSkuGet($_GET['accountId'], $_GET['skuKeywords']);

        if(!empty($skus)) {
            foreach ($skus as $sku) {
                $re[] = array(
                    'label' => $sku,
                    'sku' => $sku
                );
            }
        }
        unset($skus);

        echo json_encode($re);
        exit;
    }

    /**
     * 描述：检查最终输入的SKU是否存在
     */
    public function skuCheck() {
        $sku = array();

        $sku['sku'] = PublicInfoService::accountSkuCheck($_GET['accountId'], $_GET['skuKeywords']);
        $sku['name'] = PublicInfoService::accountSkuTitleGet($_GET['skuKeywords']);
        $sku['sellerSku'] = '';

        if ($sku['sku']) {
            $sku['sellerSku'] = PublicInfoService::accountSellerSkuGet($_GET['accountId'], $_GET['skuKeywords']);
        }
        echo json_encode($sku);
        exit;
    }

    /**
     * 描述：把前台界面的备货申请插入数据库中
     */
    public function stockingApplyInsert() {
        $stockingApplyData = json_decode($_POST['data'], true);
        //var_dump($stockingApplyData);exit;
        $moveMessage = '';
        foreach ($stockingApplyData as $key => &$data) {
            $data['sku'] = trim($data['sku']);
            $data['needs_quantity'] = trim($data['needs_quantity']);
            $data['claim_arrive_time'] = trim($data['claim_arrive_time']);

            $data['site_id'] = PublicInfoService::getSiteIdByAccountId($data['account_id']);
            $data['account_name'] = PublicInfoService::get_accounts_by_id($data['account_id'], 'name');

            $condition = array('sku' => $data['sku'],
                'export_tax_rebate' => $data['export_tax_rebate'],
                'enterprise_dominant' => $data['enterprise_dominant'],
                'site_id' => $data['site_id']
            );

            if ($data['export_tax_rebate']) {
                $quantity= $this->inventory->getTaxInventoriesInfo($condition);
            } else {
                $quantity= $this->inventory->getInventoriesInfo($condition);
            }

            if ($data['needs_quantity'] > $quantity['actual_available_num']) {
                $condition = array(
                    'sku' => $data['sku'],
                    'enterprise_dominant' => $data['enterprise_dominant'],
                    'export_tax_rebate' => $data['export_tax_rebate'],
                    'site_id' => $data['site_id'],
                    'quantity' => $data['needs_quantity']
                );

                $result = $this->inventory->auto_move_site($condition);
                if (!$result['status']) {
                    $moveMessage .=  '[' . $data['sku'] . ']:' . $result['message'];
                    unset($stockingApplyData[$key]);
                    continue;
                };
            }

            $data['status'] = (isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])
            && in_array($_SESSION['current_account']['role_id'], array(3,4))) ? 20 : 10;

            isset($_SESSION['current_account']) && !empty($_SESSION['current_account'])
            && in_array($_SESSION['current_account']['role_id'], array(5))
            && $data['buyer_id'] = $_SESSION['current_account']['id'];

            $skuCnname = PublicInfoService::getSkuCnname($data['sku']);
            $data['hs_code'] = $skuCnname['hs_code'];

            $data['create_user_id'] = $_SESSION['current_account']['id'];
            $data['create_time'] = date("Y-m-d H:i:s");

        }
        
        if (!empty($stockingApplyData)) {
            $result = $this->prepareneedsService->stockingApplyInsert($stockingApplyData);
            if ($moveMessage) {
                $result['message'] .= $moveMessage;
            }

            echo json_encode($result);
        } else {
            $result = array(
                'status' => 0,
                'message' => $moveMessage
            );

            echo json_encode($result);
        }




    }

    /**
     * 描述:获取库存占用信息，跳页展示
     */
    public function occupiedInventory() {
        $enterprise = PublicInfoService::get_company_array();
        $accounts = PublicInfoService::get_accounts();

        $info = array();
        $info['sku'] = $_GET['sku'];
        $info['export_tax_rebate'] = $_GET['export_tax_rebate'];
        $info['enterprise_dominant'] = $_GET['enterprise_dominant'];

        $this->assign('accounts', $accounts);
        $this->assign('enterprise_dominant', $enterprise);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 描述：获取占用库存报表
     */
    public function occupiedInventoryGet() {
        $info = array();

        foreach ($_POST as $key => $value) {
            if ($key == 'page') continue;
            ($value != '') && $info[$key] = $value;
        }

        $occupiedStockingNeedInventory = $this->prepareneedsService->occupiedStockingNeedInventoryGet($info);
        $occupiedInventory = $this->inboundshipmentplanService->occupiedInventoryGet($info);

        $result = array();
        if (!empty($occupiedStockingNeedInventory)) {
            foreach ($occupiedStockingNeedInventory as $value) {
                $result[] = $value;
            }
        }
        if (!empty($occupiedInventory)) {
            foreach ($occupiedInventory as $value) {
                $result[] = $value;
            }
        }

        array_walk_recursive($result, function (&$value) {
            if (!$value) {
                $value = '';
            }
        });

        $page =$_POST['page'];
        $pageSize = 20;

        $limit = $pageSize;
        $offset = ($page-1)*$pageSize;

        $total = empty($result) ? 0 : count($result);
        $totalPage = ceil($total/$pageSize);

        $resultData['total'] = $total;
        $resultData['pageSize'] = $pageSize;
        $resultData['totalPage'] = $totalPage;
        $resultData['page'] = $page;
        $resultData['result'] = array_slice($result,$offset,$limit);


        echo  json_encode($resultData);
        exit;
    }

    public function checkPurchaseOrder() {
        if ($_GET['sku'] && $_GET['enterprise_dominant']) {
            $returnMsg = $this->purchaseOrdersService->check_history_order($_GET);
            $count = count($returnMsg);

            if ($count > 1) {
                $responseMsg['allow'] = "该SKU在杭州主体也有采购单！";
                echo json_encode($responseMsg);
                exit;
            } else if ($count == 1 && !isset($returnMsg[2])) {
                $responseMsg['allow'] = "";
                echo json_encode($responseMsg);
                exit;
            } else if ($count == 1 && isset($returnMsg[2])) {
                $returnMsg = $this->purchaseOrdersService->check_timely_order($_GET);

                if(empty($returnMsg) && $_GET['enterprise_dominant'] != 2) {
                    $responseMsg['deny'] = "该SKU只在杭州主体下过采购单！";
                    echo json_encode($responseMsg);
                    exit;
                } else {
                    $responseMsg['allow'] = "该SKU在杭州主体也有采购单！";
                    echo json_encode($responseMsg);
                    exit;
                }
            } else {
                $returnMsg = $this->purchaseOrdersService->check_timely_order($_GET);

                if(empty($returnMsg)) {
                    $responseMsg['deny'] = "该SKU未下过采购单！";
                } else {
                    $responseMsg['allow'] = "";
                }

                echo json_encode($responseMsg);
                exit;
            }
        }
    }

    public function checkWarehouseOrder() {
        if ($_GET['sku'] && $_GET['enterprise_dominant']) {

            $returnMsg = $this->warehouseOrderService->checkWarehouseOrder($_GET);

            echo json_encode($returnMsg);
            exit;
        }
    }
    /**
     * 描述:判断PC单号是否存在
     * 作者:kelvin
     */
    public function checkPcId()
    {
        $model = M('prepare_needs_details','fba_','DB_FBAERP');
        $where['pc_id'] =  $_POST['pc_id'];
        if($model->where($where)->find()){
            $msg = array(
                'status' =>200,
                'msg' =>'PC单号已存在'
            );
        }else{
            $msg = array(
                'status' =>400,
                'msg' =>'PC单号不存在存在'
            );
        }
        return $this->ajaxReturn($msg);
    }
}